package com.bb.blog.mybatis.handler;

import org.apache.ibatis.type.*;
import org.springframework.util.StringUtils;


import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;



@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes({Set.class})
@Alias("VarcharToSet")
public class VarcharToSet  extends BaseTypeHandler<Set<String>> {


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Set<String> parameter, JdbcType jdbcType) throws SQLException {
        String value;
        if(parameter.isEmpty()){
            value = null;
        }else{
            value = String.join(",", parameter);
        }
        ps.setString(i, value);
    }

    @Override
    public Set<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {

        String value = rs.getString(columnName);
        if(StringUtils.isEmpty(value)){
            return Collections.emptySet();
        }
        return new HashSet<>(Arrays.asList(value.split(",")));
    }

    @Override
    public Set<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        if(StringUtils.isEmpty(value)){
            return Collections.emptySet();
        }
        return new HashSet<>(Arrays.asList(value.split(",")));
    }

    @Override
    public Set<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        if(StringUtils.isEmpty(value)){
            return Collections.emptySet();
        }
        return new HashSet<>(Arrays.asList(value.split(",")));
    }
}
